package com.redhipps.hips.client.widget;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class Dialogs {

  private static DialogBox createDialog(
      String title,
      String text,
      Widget body,
      Button... buttons) {
    final DialogBox dialogBox = new DialogBox();
    dialogBox.setText(title);
    dialogBox.setAnimationEnabled(true);

    VerticalPanel dialogVPanel = new VerticalPanel();
    dialogVPanel.setWidth("100%");
    dialogVPanel.setSpacing(2);

    Label label = new Label(text, true);
    label.setWidth("450px");
    dialogVPanel.add(label);
    dialogVPanel.setCellHorizontalAlignment(label, VerticalPanel.ALIGN_LEFT);
    
    if (body != null) {
      dialogVPanel.add(body);
      dialogVPanel.setCellHorizontalAlignment(body, VerticalPanel.ALIGN_LEFT);
    }

    HorizontalPanel hp = new HorizontalPanel();
    for (Button b : buttons) {
      hp.add(b);
    }
    dialogVPanel.add(hp);
    dialogVPanel.setCellHorizontalAlignment(hp, VerticalPanel.ALIGN_RIGHT);

    dialogBox.setWidget(dialogVPanel);
    return dialogBox;
  }

  public static void debug(String debugString) {
    info("Debug", debugString, null);
  }

  public static void info(
      String title,
      String text,
      final AsyncCallback<Void> callback) {

    Button okButton = new Button("OK");
    final DialogBox dialogBox = createDialog(title, text, null, okButton);

    okButton.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        if (callback != null) {
          callback.onSuccess(null);
        }
        dialogBox.hide();
      }
    });

    dialogBox.center();
  }

  public static void ask(
      String text,
      AsyncCallback<String> callback,
      String... choices) {
    // TODO
  }

  public static void answer(
      String title,
      String text,
      final AsyncCallback<String> callback) {
    
    final TextBox textBox = new TextBox();
    textBox.setWidth("450px");
    Button okButton = new Button("OK");
    Button cancelButton = new Button("Cancel");
    final DialogBox dialogBox = createDialog(title, text, textBox, cancelButton, okButton);

    cancelButton.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        callback.onSuccess(null);
        dialogBox.hide();
      }
    });
    okButton.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        callback.onSuccess(textBox.getText());
        dialogBox.hide();
      }
    });

    dialogBox.center();
    textBox.setFocus(true);
  }

  private Dialogs() {}
}
